package com.xiaoran.client.zk;

import com.xiaoran.client.cache.ServiceRouteCache;
import com.xiaoran.client.channel.ProviderService;
import com.xiaoran.client.config.ClientValue;
import com.xiaoran.common.annotation.RpcClient;
import org.I0Itec.zkclient.ZkClient;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * 注册服务拉取管理器
 */
@Component
public class ServicePullManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServicePullManager.class);

    @Autowired
    private ServiceRouteCache serviceRouteCache;
    @Autowired
    private ClientValue clientValue;
    @Autowired
    private ZKit zKit;

    public void pullServiceFromZK() {
        Reflections reflections = new Reflections(clientValue.getRpcClientApiPackage());
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcClient.class);
        if (CollectionUtils.isEmpty(typesAnnotatedWith)) {
            return;
        }
        for (Class<?> aClass : typesAnnotatedWith) {
            String serviceName = aClass.getName();
            List<ProviderService> providerServices = zKit.getServiceInfos(serviceName);
            //将我们从zk中查出的，缓存起来提高效率
            serviceRouteCache.addCache(serviceName, providerServices);
            //给服务器添加一个监听器当有新加入的providerService，就能立刻添加到缓存中
            zKit.subscribeZKEvent(serviceName);
        }
        
        LOGGER.info("Pull service address list from zookeeper successfully");
    }

}
